<?php


namespace app\common\business;


use think\Exception;

class GoodsSku
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\GoodsSku();
    }

    public function saveAll($data)
    {
        if (!$data['skus']) {
            return false;
        }

        foreach ($data['skus'] as $v) {
            $insert_data[] = [
                'goods_id' => $data['goods_id'],
                'specs_value_ids' => $v['propvalnames']['propvalids'],
                'price' => $v['propvalnames']['skuSellPrice'],
                'cost_price' => $v['propvalnames']['skuMarketPrice'],
                'stock' => $v['propvalnames']['skuStock'],
            ];
        }


        try {
            $res = $this->model->saveAll($insert_data);
            return $res->toArray();
        } catch (Exception $e) {
            //记录日志
            return false;
        }
    }

    public function getGoodsDetailBySkuId($id)
    {
        $data = $this->model->with('goods')->find($id);

        if (!$data) {
            return [];
        }

        if ($data->goods->status != 1) {
            return [];
        }

        return $data->toArray();
    }

    public function getSkuByGoodsId($goods_id)
    {
        try {
            $sku_data = $this->model->where(['goods_id' => $goods_id, 'status' => 1])->select();
        } catch (Exception $e) {
            return [];
        }

        return $sku_data->toArray();
    }

    public function updateStock($data)
    {
        //这里有性能瓶颈
        //好的办法是将数据先查出,然后减去已售出,然后用批量的方式去更新
        foreach ($data as $v) {
            $this->model->DecStock($v['id'], $v['num']);
        }
        return true;
    }
}